<?php
namespace app\index\model;
use think\Model;
use think\Db;

class Inventory extends Model{
    
    private $db;
    
    function __construct()
    {
        $this->db = Db::connect('db_con2');
    }

    /**
     * 根据code查询inventory
     */
    function findByCode($cno){
        if (empty($cno)) return [];
        $result = $this->db->query('select * from Inventory where cInvCode = :cno',['cno'=>$cno]);
        if (!empty($result)) {
            return $result[0];
        }
        return [];
    }

    /**
     * 查找所有A的数据
     */
    function getAll($beginPage = 0, $endPage = 20, $code = '', $itemName  ='', $modelNo = ''){
        $where = " where left(cInvCode,1) = 'A' ";
        if (!empty($code)) {
            $where .= " and cInvCode =  '".$code."'";
        }
        if (!empty($itemName)){
            $where .= " and cInvName like N'%".$itemName."%'";
        }
        if (!empty($modelNo)){
            $where .= " and cInvStd = '".$modelNo."'";
        }
        $sql = "select * from (
            　　　　select cInvName, cInvCode, cInvStd, ROW_NUMBER() OVER(Order by cInvCode ) AS RowId from Inventory $where
            　　) as b
            where RowId between $beginPage and $endPage"; 
        $result = $this->db->query($sql);
        if (!empty($result)) {
            return $result;
        }
        return [];
    }

    function getCount($code = '', $itemName = '', $modelNo = ''){
        $where = " where left(cInvCode,1) = 'A' ";
        if (!empty($code)) {
            $where .= " and cInvCode =  '".$code."'";  
        }
        if (!empty($itemName)){
            $where .= " and cInvName like N'%".$itemName."%' ";
        }
        if (!empty($modelNo)){
            $where .= " and cInvStd = '".$modelNo."'";
        } 
        $sql = "select  count(*) as count from Inventory $where ";
        $result = $this->db->query($sql);
        if (!empty($result[0])) {
            return $result[0]['count'];
        }
        return 0;
    }

    function findExchangeRate($name){
        if (empty($name)) return [];
        $result = $this->db->query('select top 1 * from exch where cexch_name = :name and itype = 2 order by i_id desc',['name'=>$name]);
        if (!empty($result)) {
            return $result[0];
        }
        return [];
    }

}
?>